/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.memory;

import com.facebook.common.logging.FLog;
import com.facebook.imageutils.BitmapUtil;
import ohos.agp.utils.Color;
import ohos.media.image.PixelMap;

import javax.annotation.Nullable;

public class BitmapPoolBackend extends LruBucketsPoolBackend<PixelMap> {

    private static final String TAG = "BitmapPoolBackend";

    @Override
    public void put(PixelMap bitmap) {
        if (isReusable(bitmap)) {
            super.put(bitmap);
        }
    }

    @Nullable
    @Override
    public PixelMap get(int size) {
        PixelMap bitmap = super.get(size);
        if (bitmap != null && isReusable(bitmap)) {
            // bitmap.eraseColor(Color.TRANSPARENT);
            bitmap.writePixels(0x00000000);
            return bitmap;
        }
        return null;
    }

    @Override
    public int getSize(PixelMap bitmap) {
        return BitmapUtil.getSizeInBytes(bitmap);
    }

    protected boolean isReusable(@Nullable PixelMap bitmap) {
        if (bitmap == null) {
            return false;
        }
        if (bitmap.isReleased()) {
            FLog.wtf(TAG, "Cannot reuse a recycled bitmap: %s", bitmap);
            return false;
        }
        if (!bitmap.isEditable()) {
            FLog.wtf(TAG, "Cannot reuse an immutable bitmap: %s", bitmap);
            return false;
        }
        return true;
    }
}
